import React, { useState, useEffect } from 'react'
import {
  Card,
  Timeline,
  Space,
  Button,
  Typography,
  Tag,
  Tooltip,
  Modal,
  Input,
  message,
  Popconfirm,
  Avatar,
  Divider,
  Empty,
  Spin,
} from 'antd'
import {
  HistoryOutlined,
  BranchesOutlined,
  RollbackOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  CopyOutlined,
  UserOutlined,
  ClockCircleOutlined,
  TagOutlined,
  DiffOutlined,
} from '@ant-design/icons'
import { formatDateTime, formatRelativeTime, copyToClipboard } from '@/utils'
import { Version } from '@/types/version'

const { Text, Paragraph } = Typography
const { TextArea } = Input

interface VersionHistoryProps {
  scriptId: string
  versions: Version[]
  loading?: boolean
  currentVersionId?: string
  onVersionSelect?: (version: Version) => void
  onVersionCompare?: (version1: Version, version2: Version) => void
  onVersionRevert?: (version: Version) => void
  onVersionDelete?: (versionId: string) => void
  onVersionComment?: (versionId: string, comment: string) => void
  showActions?: boolean
  maxHeight?: number
}

const VersionHistory: React.FC<VersionHistoryProps> = ({
  scriptId,
  versions,
  loading = false,
  currentVersionId,
  onVersionSelect,
  onVersionCompare,
  onVersionRevert,
  onVersionDelete,
  onVersionComment,
  showActions = true,
  maxHeight = 600,
}) => {
  const [selectedVersions, setSelectedVersions] = useState<string[]>([])
  const [commentModalVisible, setCommentModalVisible] = useState(false)
  const [editingVersion, setEditingVersion] = useState<Version | null>(null)
  const [commentText, setCommentText] = useState('')

  // 处理版本选择
  const handleVersionSelect = (version: Version) => {
    onVersionSelect?.(version)
  }

  // 处理版本比较选择
  const handleCompareSelect = (versionId: string) => {
    if (selectedVersions.includes(versionId)) {
      setSelectedVersions(selectedVersions.filter(id => id !== versionId))
    } else if (selectedVersions.length < 2) {
      setSelectedVersions([...selectedVersions, versionId])
    } else {
      // 替换最后一个选择
      setSelectedVersions([selectedVersions[0], versionId])
    }
  }

  // 执行版本比较
  const handleCompareVersions = () => {
    if (selectedVersions.length !== 2) {
      message.warning('请选择两个版本进行比较')
      return
    }

    const version1 = versions.find(v => v.id === selectedVersions[0])
    const version2 = versions.find(v => v.id === selectedVersions[1])
    
    if (version1 && version2) {
      onVersionCompare?.(version1, version2)
    }
  }

  // 处理版本回滚
  const handleVersionRevert = (version: Version) => {
    Modal.confirm({
      title: '确认回滚版本',
      content: (
        <div>
          <p>确定要回滚到以下版本吗？</p>
          <div style={{ 
            padding: 12, 
            background: '#f5f5f5', 
            borderRadius: 6,
            marginTop: 8,
          }}>
            <div><strong>版本:</strong> {version.version_number}</div>
            <div><strong>时间:</strong> {formatDateTime(version.created_at)}</div>
            <div><strong>创建者:</strong> {version.created_by}</div>
            {version.comment && (
              <div><strong>备注:</strong> {version.comment}</div>
            )}
          </div>
          <p style={{ marginTop: 12, color: '#ff4d4f' }}>
            注意：回滚操作将创建一个新版本，当前版本不会被删除。
          </p>
        </div>
      ),
      okText: '确认回滚',
      cancelText: '取消',
      onOk: () => onVersionRevert?.(version),
    })
  }

  // 处理版本删除
  const handleVersionDelete = (version: Version) => {
    if (version.id === currentVersionId) {
      message.error('不能删除当前版本')
      return
    }

    onVersionDelete?.(version.id)
  }

  // 处理添加备注
  const handleAddComment = (version: Version) => {
    setEditingVersion(version)
    setCommentText(version.comment || '')
    setCommentModalVisible(true)
  }

  // 保存备注
  const handleSaveComment = async () => {
    if (!editingVersion) return

    try {
      await onVersionComment?.(editingVersion.id, commentText)
      message.success('备注已保存')
      setCommentModalVisible(false)
      setEditingVersion(null)
      setCommentText('')
    } catch (error) {
      message.error('保存备注失败')
    }
  }

  // 复制版本内容
  const handleCopyContent = async (version: Version) => {
    const success = await copyToClipboard(version.content)
    if (success) {
      message.success('版本内容已复制到剪贴板')
    } else {
      message.error('复制失败')
    }
  }

  // 获取版本状态标签
  const getVersionStatusTag = (version: Version) => {
    if (version.id === currentVersionId) {
      return <Tag color="blue">当前版本</Tag>
    }
    if (version.is_major) {
      return <Tag color="gold">主要版本</Tag>
    }
    return <Tag color="default">历史版本</Tag>
  }

  // 渲染时间线项
  const renderTimelineItem = (version: Version, index: number) => {
    const isSelected = selectedVersions.includes(version.id)
    const isCurrent = version.id === currentVersionId
    
    return (
      <Timeline.Item
        key={version.id}
        dot={
          <Avatar 
            size="small" 
            icon={<BranchesOutlined />}
            style={{ 
              backgroundColor: isCurrent ? '#1890ff' : '#f0f0f0',
              color: isCurrent ? '#fff' : '#666',
            }}
          />
        }
        color={isCurrent ? 'blue' : 'gray'}
      >
        <Card 
          size="small"
          style={{ 
            marginBottom: 8,
            border: isSelected ? '2px solid #1890ff' : '1px solid #f0f0f0',
            cursor: 'pointer',
          }}
          onClick={() => handleVersionSelect(version)}
          bodyStyle={{ padding: '12px 16px' }}
        >
          {/* 版本头部信息 */}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ flex: 1 }}>
              <Space size="small" wrap>
                <Text strong>v{version.version_number}</Text>
                {getVersionStatusTag(version)}
                <Text type="secondary" style={{ fontSize: 12 }}>
                  <ClockCircleOutlined style={{ marginRight: 4 }} />
                  {formatRelativeTime(version.created_at)}
                </Text>
              </Space>
              
              <div style={{ marginTop: 4 }}>
                <Space size="small">
                  <UserOutlined style={{ fontSize: 12, color: '#666' }} />
                  <Text style={{ fontSize: 12, color: '#666' }}>
                    {version.created_by}
                  </Text>
                  <Text style={{ fontSize: 12, color: '#666' }}>
                    {formatDateTime(version.created_at)}
                  </Text>
                </Space>
              </div>
            </div>

            {showActions && (
              <Space size="small">
                {/* 比较选择 */}
                <Tooltip title={isSelected ? '取消选择' : '选择比较'}>
                  <Button
                    type={isSelected ? 'primary' : 'text'}
                    size="small"
                    icon={<DiffOutlined />}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleCompareSelect(version.id)
                    }}
                  />
                </Tooltip>

                {/* 查看内容 */}
                <Tooltip title="查看内容">
                  <Button
                    type="text"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleVersionSelect(version)
                    }}
                  />
                </Tooltip>

                {/* 复制内容 */}
                <Tooltip title="复制内容">
                  <Button
                    type="text"
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleCopyContent(version)
                    }}
                  />
                </Tooltip>

                {/* 添加备注 */}
                <Tooltip title="添加备注">
                  <Button
                    type="text"
                    size="small"
                    icon={<EditOutlined />}
                    onClick={(e) => {
                      e.stopPropagation()
                      handleAddComment(version)
                    }}
                  />
                </Tooltip>

                {/* 回滚版本 */}
                {!isCurrent && (
                  <Tooltip title="回滚到此版本">
                    <Button
                      type="text"
                      size="small"
                      icon={<RollbackOutlined />}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleVersionRevert(version)
                      }}
                    />
                  </Tooltip>
                )}

                {/* 删除版本 */}
                {!isCurrent && (
                  <Popconfirm
                    title="确定删除此版本吗？"
                    onConfirm={(e) => {
                      e?.stopPropagation()
                      handleVersionDelete(version)
                    }}
                    okText="删除"
                    cancelText="取消"
                  >
                    <Tooltip title="删除版本">
                      <Button
                        type="text"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={(e) => e.stopPropagation()}
                      />
                    </Tooltip>
                  </Popconfirm>
                )}
              </Space>
            )}
          </div>

          {/* 版本备注 */}
          {version.comment && (
            <div style={{ marginTop: 8 }}>
              <Text style={{ fontSize: 12, color: '#666' }}>
                <TagOutlined style={{ marginRight: 4 }} />
                {version.comment}
              </Text>
            </div>
          )}

          {/* 版本统计 */}
          <div style={{ marginTop: 8, fontSize: 11, color: '#999' }}>
            <Space split={<Divider type="vertical" />}>
              <span>大小: {(version.content.length / 1024).toFixed(1)}KB</span>
              <span>行数: {version.content.split('\n').length}</span>
              {version.changes_summary && (
                <span>变更: {version.changes_summary}</span>
              )}
            </Space>
          </div>
        </Card>
      </Timeline.Item>
    )
  }

  if (loading) {
    return (
      <Card>
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
          <div style={{ marginTop: 16 }}>
            <Text type="secondary">加载版本历史中...</Text>
          </div>
        </div>
      </Card>
    )
  }

  if (versions.length === 0) {
    return (
      <Card>
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂无版本历史"
        />
      </Card>
    )
  }

  return (
    <Card
      title={
        <Space>
          <HistoryOutlined />
          <span>版本历史</span>
          <Text type="secondary">({versions.length})</Text>
        </Space>
      }
      extra={
        showActions && selectedVersions.length === 2 && (
          <Button
            type="primary"
            size="small"
            icon={<DiffOutlined />}
            onClick={handleCompareVersions}
          >
            比较版本
          </Button>
        )
      }
    >
      {/* 选择提示 */}
      {showActions && selectedVersions.length > 0 && (
        <div style={{ 
          marginBottom: 16, 
          padding: 8, 
          background: '#e6f7ff', 
          borderRadius: 6,
          fontSize: 12,
        }}>
          <Space>
            <Text>已选择 {selectedVersions.length} 个版本</Text>
            {selectedVersions.length === 2 && (
              <Text type="secondary">点击"比较版本"查看差异</Text>
            )}
            <Button 
              type="link" 
              size="small"
              onClick={() => setSelectedVersions([])}
            >
              清除选择
            </Button>
          </Space>
        </div>
      )}

      {/* 版本时间线 */}
      <div style={{ maxHeight, overflow: 'auto' }}>
        <Timeline mode="left">
          {versions.map((version, index) => renderTimelineItem(version, index))}
        </Timeline>
      </div>

      {/* 备注编辑模态框 */}
      <Modal
        title="编辑版本备注"
        open={commentModalVisible}
        onOk={handleSaveComment}
        onCancel={() => {
          setCommentModalVisible(false)
          setEditingVersion(null)
          setCommentText('')
        }}
        okText="保存"
        cancelText="取消"
      >
        {editingVersion && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>版本: </Text>
              <Text>v{editingVersion.version_number}</Text>
              <Text type="secondary" style={{ marginLeft: 16 }}>
                {formatDateTime(editingVersion.created_at)}
              </Text>
            </div>
            
            <TextArea
              value={commentText}
              onChange={(e) => setCommentText(e.target.value)}
              placeholder="输入版本备注..."
              rows={4}
              maxLength={500}
              showCount
            />
          </div>
        )}
      </Modal>
    </Card>
  )
}

export default VersionHistory